/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.servlets.pages;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import ru.miit.elearning.hibernate.dao.ConfigurationDAO;
import ru.miit.elearning.hibernate.dao.HibernateUtil;
import ru.miit.elearning.hibernate.dao.UserDAO;
import ru.miit.elearning.hibernate.dao.WebLabUtil;
import ru.miit.elearning.hibernate.dto.AdditionalProperty;
import ru.miit.elearning.hibernate.dto.ProfileType;
import ru.miit.elearning.hibernate.dto.UserIdentity;

/**
 *
 * @author Cyclone
 */
public class ProfileServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        //PrintWriter out = response.getWriter();

        Session session = null;
        String message = null;

        try {
            int id = -1;
            boolean isMyProfile = false;
            boolean isStudent = false;
            boolean isTutor = false;

            String idString = request.getParameter("id");

            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            UserDAO userDAO = new UserDAO(session);

            // to find out is user requesting his own profile
            int currentUserId = userDAO.findUserIdByLogin(request.getRemoteUser());

            if (idString == null) {
                id = currentUserId;
                isMyProfile = true;
            } else {
                id = Integer.parseInt(idString);
                if (id == currentUserId) {
                    isMyProfile = true;
                }
            }

            if (isMyProfile) {
                isStudent = request.isUserInRole("student");
                isTutor = request.isUserInRole("tutor");
            } else {
                isStudent = userDAO.isUserInRoleStudent(id);
                isTutor = userDAO.isUserInRoleTutor(id);
            }

            request.setAttribute("isStudent", isStudent);
            request.setAttribute("isTutor", isTutor);

            UserIdentity userIdentity = userDAO.findUserById(id);
            if (userDAO.isUserInRoleStudent(id)) {

                if (isMyProfile) {
                    request.setAttribute("courseList", userDAO.findCoursesByStudentId(id));
                } else {

                    if (request.isUserInRole("admin")) {
                        request.setAttribute("courseList", userDAO.findCoursesByStudentId(id));
                    } else {
                        if (request.isUserInRole("tutor")) {
                            request.setAttribute("courseList", userDAO.findCoursesByStudentIdByTutor(id, currentUserId));
                        }
                    }
                }
            }

            if (userDAO.isUserInRoleTutor(id)) {
                request.setAttribute("tutorCourseList", userDAO.findCoursesByTutorId(id));
            }



            try {
                ConfigurationDAO configurationDAO = new ConfigurationDAO(session);
                List<AdditionalProperty> propertyList = configurationDAO.findUserPropertiesByNoUser(id);
                request.setAttribute("propertyList", propertyList);
            } catch (Exception e) {
                e.printStackTrace();
                String propError = "Ошибка запроса списка доступных дополнительных свойств<br/>";
                if (message != null) {
                    message += propError;
                } else {
                    message = propError;
                }
            }


            request.setAttribute("user", userIdentity);

            if (request.isUserInRole("admin")) {
                List<ProfileType> profileTypeList = userDAO.findProfileTypesByNoUser(id);
                request.setAttribute("profileTypeList", profileTypeList);
            }

            if (message != null) {
                getServletContext().setAttribute("message", message);
            }

            request.setAttribute("isMyProfile", isMyProfile);
            getServletContext().getRequestDispatcher("/profile.jsp").forward(request, response);
            session.getTransaction().commit();


        } catch (Exception e) {
            if (session != null && session.isOpen()) {
                session.getTransaction().rollback();
            }
            Logger.getLogger(ProfileServlet.class.getName()).log(Level.SEVERE, null, e);
            e.printStackTrace();

            message = "<p>Ошибка запроса профиля";
            message += WebLabUtil.prepareExceptionRef(request.getSession(), e);
            message += "</p>";
            getServletContext().setAttribute("message", message);

//            getServletContext().getRequestDispatcher("/profile.jsp").forward(request, response);
            response.sendRedirect("Users");
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        //out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
